/**
 * @Description: TODO
 * @author: gongth
 * @date: 2022年08月29日 14:19
 */
package me.zhengjie.weixin;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.mi.old.StringUtil;

@Slf4j
public class WxAccessTokenUtil {

    private static String ACCESS_TOKEN;
    private static Long EXPIRES_IN;

//    https请求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
    public static synchronized String getAccessToken(){
        if(StringUtil.isEmpty(ACCESS_TOKEN) || (EXPIRES_IN - System.currentTimeMillis())/1000/60 < 5){

            String url = WeiXinConfig.apiUrl+"/cgi-bin/token?grant_type=client_credential&appid="+WeiXinConfig.appId+"&secret="+WeiXinConfig.secretKey;
            String res = HttpUtil.get(url);

            log.info("微信获取ACCESS_TOKEN {} ",res);
            JSONObject accessTokenJson= JSONObject.parseObject(res);
            if(accessTokenJson.containsKey("errcode") && accessTokenJson.getInteger("errcode") != 0){

                log.error("微信获取ACCESS_TOKEN错误 {} ",res);
            }else{
                ACCESS_TOKEN = accessTokenJson.getString("access_token");
                int expiresInSec = accessTokenJson.getInteger("expires_in");
                EXPIRES_IN = System.currentTimeMillis() + expiresInSec*1000;
            }
        }
        return ACCESS_TOKEN;
    }
}

   